<template>
  <div :id="mapContainerId" :style="{ height: `${height}vh` }"></div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
  import gcoord from 'gcoord';
  import AMapLoader from '@amap/amap-jsapi-loader';
  // 需要引入相关的API方法
  import { getStationById, getStationByOrgId } from '@/api/business/stationManager/station';
  import { getFenceByStationId } from '@/api/business/fenceManager/fence';
  import { getTracksByStationId } from '@/api/business/stationManager/track';

  // 定义组件属性
  const props = withDefaults(
    defineProps<{
      orgId?: string;
      isDraw?: boolean;
      drawOption?: {
        fence?: boolean;
        track?: boolean;
      };
      zoom?: number;
      height?: number;
      stationId?: string;
    }>(),
    {
      orgId: '',
      isDraw: false,
      drawOption: () => ({
        fence: false,
        track: false,
      }),
      zoom: 16,
      height: 100,
      stationId: '',
    }
  );

  // 定义事件发射
  const emit = defineEmits<{
    (e: 'cabinet', data: any): void;
  }>();

  // 响应式数据
  const mapContainerId = ref('map-container-' + Date.now());
  let map: any = null;
  let tileLayerOverlay: any = null;
  let tileLayerSatellite: any = null;
  let mouseTool: any = null;
  let fencePolygon: any = null;
  let stationData: any = null;
  let fenceData: any = null;
  let tracksData: any = null;
  let trackPolylines: any[] = []; // 存储线路
  let trackWhiteDashedLines: any[] = []; // 存储白色虚线
  let trackMarkers: any[] = []; // 存储标记点

  // 获取地图服务基础URL
  function getMapBaseUrl() {
    // 这里应该从配置或环境变量中获取
    return import.meta.env.VITE_MAP_BASE_URL || '';
  }

  // 加载站点数据（通过ID）
  async function loadStationDataById(id: string) {
    try {
      
      stationData = await getStationById({ id });
      await initMap();

      if (stationData) {
        if (props.drawOption?.fence) {
          await loadFence();
        }
        if (props.drawOption?.track) {
          await loadTracks();
        }
      }
    } catch (error) {
      console.error('加载站点数据失败:', error);
    }
  }

  // 加载站点数据（通过组织ID）
  async function loadStationData(orgId) {
    
    if (!orgId) {
      await initMap();
      return;
    }
    try {
      stationData = await getStationByOrgId({ orgId: orgId });
      await initMap();
      if (stationData) {
        if (props.drawOption?.fence) {
          await loadFence();
        }
        if (props.drawOption?.track) {
          await loadTracks();
        }
      }
    } catch (error) {
      console.error('加载站点数据失败:', error);
    }
  }

  // 初始化地图
  async function initMap() {
    if (!stationData) {
      // 清除页面加载的地图
      // 当 stationData 不存在时，清除页面上已加载的地图
      if (map) {
        map.destroy();
        map = null;
      } else {
        // 确保AMap已经加载
        await loadAMapScript();
        map = new AMap.Map(mapContainerId.value, {
          resizeEnable: true,
          expandZoomRange: true,
          viewMode: '2D',
          zoom: 5,
          zooms: [3, 21],
          center: [116.397428, 39.90923], // 北京坐标
        });

        // map.destroy();
        // map = null;
      }
      return;
    }

    // 确保AMap已经加载
    await loadAMapScript();

    // 清除已有图层
    clearMapLayers();

    // 确保地图容器存在
    if (!document.getElementById(mapContainerId.value)) {
      await new Promise((resolve) => setTimeout(resolve, 100));
    }

    // 初始化地图
    map = new AMap.Map(mapContainerId.value, {
      resizeEnable: true,
      expandZoomRange: true,
      viewMode: '2D',
      zoom: stationData.offlineZoom,
      zooms: [stationData.offlineZoom, 21],
      center: [stationData.centerLongitude, stationData.centerLatitude],
    });

    // 等待地图初始化完成
    await new Promise((resolve) => {
      map.on('complete', resolve);
    });

    // 创建瓦片图层
    tileLayerOverlay = new AMap.TileLayer({
      getTileUrl: (x, y, z) =>
        getMapBaseUrl() + stationData.offlineFilePath + 'overlay/' + z + '/' + x + '/' + y + '.png',
      zIndex: 11, // 确保标注图层在上层
    });

    tileLayerSatellite = new AMap.TileLayer.Satellite({
      getTileUrl: (x, y, z) =>
        getMapBaseUrl() +
        stationData.offlineFilePath +
        'satellite/' +
        z +
        '/' +
        x +
        '/' +
        y +
        '.jpg',
      zIndex: 10, // 卫星图层在下层
    });

    // 添加图层
    map.add(tileLayerSatellite);
    map.add(tileLayerOverlay);

    // 设置地图旋转角度
    map.setRotation(stationData.mapRotate || 0);
  }

  // 动态加载AMap脚本
  function loadAMapScript() {
    return new Promise((resolve, reject) => {
      // 检查AMap是否已经存在
      if (typeof AMap !== 'undefined') {
        resolve(AMap);
        return;
      }

      // 使用AMapLoader加载
      AMapLoader.load({
        key: 'key值', // 高德地图key
        version: '1.4.15',
        plugins: ['AMap.MouseTool', 'AMap.Marker', 'AMap.Polyline'], // 需要使用的插件列表
      })
        .then((AMap) => {
          resolve(AMap);
        })
        .catch((error) => {
          console.error('地图加载失败：', error);
          reject(error);
        });
    });
  }

  // 清除地图图层
  function clearMapLayers() {
    if (map) {
      // 清除所有覆盖物
      map.clearMap();
      // 清空线路和标记数组
      trackPolylines = [];
      trackWhiteDashedLines = [];
      trackMarkers = [];
    }
  }

  // 加载电子围栏
  async function loadFence() {
    if (!stationData?.stationId) return;

    try {
      const res = await getFenceByStationId({ stationId: stationData.stationId });
      // 根据实际API返回结构调整
      fenceData = res?.data || res;
      renderFence();
    } catch (error) {
      console.error('加载围栏数据失败:', error);
    }
  }

  // 渲染电子围栏
  function renderFence() {
    if (!fenceData || !map) return;

    // 清除已有围栏
    clearFence();

    // 根据实际API返回结构调整访问方式
    const coordinates = fenceData.coordinatesList || fenceData.coordinates || [];
    if (coordinates && coordinates.length > 0) {
      // 转换坐标
      const path = coordinates.map((coord: any) => {
        // WGS84转GCJ02
        const transformed = gcoord.transform(
          [coord.longitude, coord.latitude],
          gcoord.WGS84,
          gcoord.GCJ02
        );
        return new AMap.LngLat(transformed[0], transformed[1]);
      });

      // 创建多边形
      fencePolygon = new AMap.Polygon({
        path: path,
        strokeColor: '#d03050',
        strokeOpacity: 0.6,
        strokeWeight: 2,
        fillColor: '#d03050',
        fillOpacity: 0.3,
        strokeStyle: 'dashed',
      });

      // 添加到地图
      map.add(fencePolygon);
    }
  }

  // 加载轨道线路
  async function loadTracks() {
    if (!stationData?.stationId) return;

    try {
      const res = await getTracksByStationId({ stationId: stationData.stationId });
      // 根据实际API返回结构调整
      tracksData = res?.data || res;
      renderTracks();
    } catch (error) {
      console.error('加载轨道数据失败:', error);
    }
  }

  // 渲染轨道线路和标记点（只在首尾两端展示标记点）
  function renderTracks() {
    if (!tracksData || !map) return;

    // 清除已有线路和标记
    clearTracks();

    // 如果tracksData是对象，尝试访问其列表属性
    const trackList = Array.isArray(tracksData)
      ? tracksData
      : tracksData.list || tracksData.tracks || [tracksData];

    trackList.forEach((track) => {
      // 根据实际API返回结构调整访问方式
      const coordinates = track.coordinatesList || track.coordinates || [];
      if (coordinates && coordinates.length > 0) {
        // 转换坐标
        const path = coordinates.map((coord: any) => {
          // WGS84转GCJ02
          const transformed = gcoord.transform(
            [coord.longitude, coord.latitude],
            gcoord.WGS84,
            gcoord.GCJ02
          );
          return new AMap.LngLat(transformed[0], transformed[1]);
        });

        // 创建黑色实线
        const polyline = new AMap.Polyline({
          path: path,
          strokeColor: '#333', // 黑色或深灰色
          strokeWeight: 4, // 线宽
          strokeOpacity: 1,
          strokeStyle: 'solid',
          lineCap: 'round', // 线头圆角
          lineJoin: 'round',
        });

        // 创建白色虚线，与黑线重叠显示
        const whiteDashedLine = new AMap.Polyline({
          path: path,
          strokeColor: '#FFFFFF', // 白色
          strokeWeight: 4,
          strokeOpacity: 1,
          strokeStyle: 'dashed',
          strokeDasharray: [5, 10], // 虚线间隔：5px 实线，10px 空白
          lineCap: 'round',
          lineJoin: 'round',
        });

        // 添加到地图
        map.add(polyline);
        map.add(whiteDashedLine);
        // 保存到数组中以便后续清除
        trackPolylines.push(polyline);
        trackWhiteDashedLines.push(whiteDashedLine);

        // 只在首尾两端创建标记点
        const endpoints = [coordinates[0], coordinates[coordinates.length - 1]];
        endpoints.forEach((coord: any, index: number) => {
          // 转换坐标
          const transformed = gcoord.transform(
            [coord.longitude, coord.latitude],
            gcoord.WGS84,
            gcoord.GCJ02
          );

          // 创建自定义样式标记点
          const marker = new AMap.Marker({
            position: new AMap.LngLat(transformed[0], transformed[1]),
            title: track.trackName || `标记点${index === 0 ? 'A' : 'B'}`,
            // 使用自定义标记内容
            content: `<div style="
              border-radius: 0.25rem;
              background-color: rgb(0, 150, 136);
              width: 3rem;
              height: 1.6rem;
              border: 2px solid rgb(120, 222, 199);
              box-shadow: rgba(114, 124, 245, 0.5) 0px 2px 6px 0px;
              text-align: center;
              font-size: 0.8rem;
              color: white;
              opacity: 1;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: bold;
            ">${track.trackName || (index === 0 ? 'A' : 'B')}</div>`,
            offset: new AMap.Pixel(-24, -13), // 调整标记点位置使其居中
          });

          // 添加到地图
          map.add(marker);
          // 保存到数组中以便后续清除
          trackMarkers.push(marker);
        });
      }
    });
  }

  // 清除轨道线路和标记
  function clearTracks() {
    // 清除线路
    if (trackPolylines.length > 0) {
      trackPolylines.forEach((polyline) => {
        polyline.setMap(null);
      });
      trackPolylines = [];
    }

    // 清除白色虚线
    if (trackWhiteDashedLines.length > 0) {
      trackWhiteDashedLines.forEach((line) => {
        line.setMap(null);
      });
      trackWhiteDashedLines = [];
    }

    // 清除标记
    if (trackMarkers.length > 0) {
      trackMarkers.forEach((marker) => {
        marker.setMap(null);
      });
      trackMarkers = [];
    }
  }

  // 开始绘制围栏
  function drawFence() {
    if (!map) return;

    // 初始化鼠标工具
    if (!mouseTool) {
      mouseTool = new AMap.MouseTool(map);

      // 开始绘制多边形
      mouseTool.polygon({
        strokeColor: '#d03050',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#d03050',
        fillOpacity: 0.3,
        strokeStyle: 'dashed',
      });

      // 监听绘制完成事件
      mouseTool.on('draw', function (e: any) {
        // 清除之前的围栏
        if (fencePolygon) {
          fencePolygon.setMap(null);
          fencePolygon = null;
        }

        // 保存新绘制的围栏
        fencePolygon = e.obj;
      });
    } else {
      // 开始绘制多边形
      mouseTool.polygon({
        strokeColor: '#d03050',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#d03050',
        fillOpacity: 0.3,
        strokeStyle: 'dashed',
      });
    }
  }

  // 获取当前绘制的围栏
  function getFence() {
    return fencePolygon;
  }

  // 清除围栏
  function clearFence() {
    if (fencePolygon) {
      fencePolygon.setMap(null);
      fencePolygon = null;
    }

    // 如果处于绘制状态，重新开始绘制
    if (props.isDraw) {
      drawFence();
    }
  }

  // 设置地图旋转角度
  function setRotate(angle: number) {
    if (map) {
      map.setRotation(angle || 0);
    }
  }

  // 关闭绘制工具
  function closeDrawTool() {
    if (mouseTool) {
      mouseTool.close();
      mouseTool = null;
    }
  }

  // 监听绘制状态变化
  watch(
    () => props.isDraw,
    (newVal) => {
      if (newVal) {
        // 进入绘制模式
        drawFence();
      } else {
        // 退出绘制模式
        closeDrawTool();
      }
    }
  );

  // 组件挂载
  onMounted(() => {
    nextTick(() => {
      if (props.stationId) {
        loadStationDataById(props.stationId);
      } else if (props.orgId) {
        loadStationData(props.orgId);
      } else {
        loadStationData(null);
      }
    });
  });

  // 组件卸载
  onUnmounted(() => {
    closeDrawTool();
    clearTracks();
    if (map) {
      map.destroy();
      map = null;
    }
  });

  // 暴露方法给父组件
  defineExpose({
    loadStationData,
    loadStationDataById,
    loadFence,
    loadTracks,
    drawFence,
    clearFence,
    clearTracks,
    getFence,
    setRotate,
  });
</script>

<style scoped>
  #map-container {
    width: 100%;
  }
</style>
